package file;

import com.sun.jna.Platform;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileOperating {


    /**
     * 向文件中写入pid号
     *
     * @param append   : 是否在文件中追加
     * @param filePath ： 文件路径
     * @param pid：     pid号
     * @throws IOException
     */
    public synchronized static void writeFile(boolean append, String filePath, String pid) throws IOException {
        if (Platform.isWindows()) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(filePath, append);
        writer.write(pid + "\n");
        writer.close();
    }

    /**
     * 从文件中读pid号
     * @param filePath
     * @return
     * @throws IOException
     */
    public synchronized static List<String> readFile(String filePath) throws IOException {
        if (!new File(filePath).exists()) {
            return null;
        }
        String line;
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        List<String> list = new ArrayList<>();
        while (StringUtils.isNotBlank(line = reader.readLine())) {
            list.add(line.trim());
        }
        reader.close();
        return list;
    }

}
